package com.sweetcircle.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.sweetcircle.domain.dto.MessageSendDto;
import com.sweetcircle.domain.dto.TokenUserInfoDto;
import com.sweetcircle.domain.enums.MessageTypeEnum;
import com.sweetcircle.domain.po.ChatMessage;
import com.sweetcircle.domain.po.UserContact;
import com.sweetcircle.exception.BusinessException;
import com.sweetcircle.mapper.ChatMessageMapper;
import com.sweetcircle.utils.AnanUtils;
import com.sweetcircle.utils.RedisComponet;
import com.sweetcircle.websocket.MessageHandler;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;


/**
 * 聊天消息表 业务接口实现
 */
@Service("chatMessageService")
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService {

    @Resource
    private MessageHandler messageHandler;

    @Resource
    private UserContactService userContactService;

    @Resource
    private RedisComponet redisComponet;

    @Override
    public ChatMessage sendMessage(ChatMessage chatMessage, TokenUserInfoDto tokenUserInfoDto) {

        // 强制下线
        if (MessageTypeEnum.FORCE_OFF_LINE.getType().equals(chatMessage.getMessageType())) {
            MessageSendDto messageSendDto = AnanUtils.copyBean(chatMessage, MessageSendDto.class);
            messageHandler.sendMessage(messageSendDto);
            return null;
        }
        // 设置群聊Id
        chatMessage.setGroupId(chatMessage.getContactId());
        // 设置消息id
        chatMessage.setMessageId(AnanUtils.MD5Encryption(String.valueOf(System.currentTimeMillis()), "messageId"));

        // 查看该用户是否 在线
        Long lastHeartBeat = redisComponet.getUserHeartBeat(chatMessage.getContactId());
        if (lastHeartBeat == null) {  // 不在线 发送离线消息
            chatMessage.setSendStatus(2);  // 发送状态 未接收
        }

        // 判断 是否是对方好友 是否还在群聊中 是否被对方拉黑
        UserContact one = userContactService.getOne(new LambdaQueryWrapper<UserContact>()
                .eq(UserContact::getUserId, chatMessage.getSendUserId())
                .eq(UserContact::getContactUserId, chatMessage.getContactId())
                .eq(UserContact::getStatus, 1)// 获取联系人信息
        );
        // ("状态 0:非好友 1:好友 2:已删除好友 3:被好友删除 4:已拉黑好友 5:被好友拉黑")
        if (one == null || one.getFriendsCode() == 3) {
            throw new BusinessException(901, "你还不是对方好友");
            //("状态 0:非好友 1:好友 2:已删除好友 3:被好友删除 4:已拉黑好友 5:被好友拉黑")
        } else if (one.getFriendsCode() == 5) {
            throw new BusinessException(902, "对方拒绝接收你的消息");
        }

        boolean save = save(chatMessage);
        if (!save) {
            throw new BusinessException(400, "发送消息失败");
        }
        MessageSendDto messageSendDto = AnanUtils.copyBean(chatMessage, MessageSendDto.class);
        if (lastHeartBeat != null) {
            messageHandler.sendMessage(messageSendDto);
        }

        return chatMessage;
    }

    public ChatMessage sendFileMessage(ChatMessage chatMessage, TokenUserInfoDto tokenUserInfoDto) {







        return null;
    }

    @Override
    public void saveMessageFile(String userId, Long messageId, MultipartFile file, MultipartFile cover) {

    }

    @Override
    public File downloadFile(TokenUserInfoDto userInfoDto, Long messageId, Boolean cover) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMessage(ChatMessage chatMessage) {
        boolean list = SqlHelper.retBool(count(new LambdaQueryWrapper<ChatMessage>().eq(ChatMessage::getSessionId, chatMessage.getSessionId()).eq(ChatMessage::getStatus, 1)));
        if (!list) {
            return true;
        }
        boolean remove = remove(new LambdaQueryWrapper<ChatMessage>().eq(ChatMessage::getSessionId, chatMessage.getSessionId()).eq(ChatMessage::getStatus, 1));
        if (!remove) {
            throw new BusinessException(400, "删除消息失败");
        }
        return true;
    }
}
